package Controllers

import (
	"gorm-gin-master/ApiHelpers"
	"gorm-gin-master/Models"
	"github.com/gin-gonic/gin"
)

// 查询全部数据
func ListBook(c *gin.Context) {
	var book []Models.Book
	err := Models.GetAllBook(&book)
	if err != nil {
		ApiHelpers.RespondJSON(c, 404, "未获取到数据", book)
	} else {
		ApiHelpers.RespondJSON(c, 200,"获取数据成功", book)
	}
}

// 添加数据
func AddNewBook(c *gin.Context) {
	var book Models.Book
	c.BindJSON(&book)
	err := Models.AddNewBook(&book)
	if err != nil {
		ApiHelpers.RespondJSON(c, 404,"添加数据失败", book)
	} else {
		ApiHelpers.RespondJSON(c, 200,"添加数据成功", book)
	}
}

// 查询某一条数据
func GetOneBook(c *gin.Context) {
	id := c.Params.ByName("id")
	var book Models.Book
	err := Models.GetOneBook(&book, id)
	if err != nil {
		ApiHelpers.RespondJSON(c, 404,"查询数据失败", book)
	} else {
		ApiHelpers.RespondJSON(c, 200,"查询数据成功", book)
	}
}

// 修改某一条数据
func PutOneBook(c *gin.Context) {
	var book Models.Book
	id := c.Params.ByName("id")
	err := Models.GetOneBook(&book, id)
	if err != nil {
		ApiHelpers.RespondJSON(c, 404,"未查询到数据", book)
	}
	c.BindJSON(&book)
	err = Models.PutOneBook(&book, id)
	if err != nil {
		ApiHelpers.RespondJSON(c, 404,"修改数据失败", book)
	} else {
		ApiHelpers.RespondJSON(c, 200,"修改数据成功", book)
	}
}

// 删除某一条数据
func DeleteBook(c *gin.Context) {
	var book Models.Book
	id := c.Params.ByName("id")
	err := Models.DeleteBook(&book, id)
	if err != nil {
		ApiHelpers.RespondJSON(c, 404,"删除数据失败", book)
	} else {
		ApiHelpers.RespondJSON(c, 200,"删除数据成功", book)
	}
}
